# -*- coding: utf-8 -*-

import VBAPI
from win32com import client
from enum import Enum
import traceback

def get_paraval(value, type):
    para_type = type
    para_value = value
    if para_type == 2:
        paraval = para_value.BoolValue
    elif para_type == 3:
        paraval = para_value.DoubleValue
    elif para_type == 1:
        paraval = para_value.IntValue
    elif para_type == 0:
        paraval = para_value.StringValue
    else:
        paraval = para_value.NoteId
    return paraval
class modeltype(Enum):
    EpfcMDL_2D_SECTION = 3  # from enum EpfcModelType
    EpfcMDL_ASSEMBLY = 0  # from enum EpfcModelType
    EpfcMDL_DIAGRAM = 9  # from enum EpfcModelType
    EpfcMDL_DRAWING = 2  # from enum EpfcModelType
    EpfcMDL_DWG_FORMAT = 5  # from enum EpfcModelType
    EpfcMDL_LAYOUT = 4  # from enum EpfcModelType
    EpfcMDL_MARKUP = 8  # from enum EpfcModelType
    EpfcMDL_MFG = 6  # from enum EpfcModelType
    EpfcMDL_PART = 1  # from enum EpfcModelType
    EpfcMDL_REPORT = 7  # from enum EpfcModelType
    EpfcModelType_nil = 10  # from enum EpfcModelType
class IModel(object):


    def __init__(self, filename):
        self.filename =filename
        self.model = self.ICreate()
        self.SheetNumber = self.ICurrentSheetNumber()

    def ICreate(self):
        ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
        mdlDescr = ModelDescriptor.CreateFromFileName(self.filename)
        RetrieveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
        options = RetrieveModelOptions.Create()
        options.AskUserAboutReps = False
        model = AsyncConnection.Session.RetrieveModelWithOpts(mdlDescr, options)
        return model

    def IListFeaturesByType(self, options, feattype):
        return self.model.ListFeaturesByType(options, getattr(VBAPI.constants, feattype))

    def ISetSheetFormat(self, SheetNumber, Format, FormatSheetNumber, DrawingModel):
        self.model.SetSheetFormat(SheetNumber, Format, FormatSheetNumber, DrawingModel)

    def ICurrentSheetNumber(self):
        print(self.model)
        return self.model.CurrentSheetNumber

    def IGetSheetFormat(self):
        return self.model.GetSheetFormat(self.SheetNumber)





def ChangeDrwFormat(DrwName, FormatName):
    DrwModel = IModel(DrwName)
    FormatModel = IModel(FormatName)
    SheetNumber = DrwModel.ICurrentSheetNumber()
    SheetFormat = FormatModel.IGetSheetFormat()
    FormatSheetNumber = FormatModel.ICurrentSheetNumber()
    DrwModel.ISetSheetFormat(SheetNumber, SheetFormat, FormatSheetNumber, DrwModel)

def get_modellist(filename):
    model = IModel(filename)
    items = model.IListFeaturesByType(True, 'EpfcFEATTYPE_COMPONENT')
    for item in items:
        item_Descr = item.ModelDescr
        print(item_Descr.GetFileName())
        if item_Descr.GetExtension() == 'asm':
            get_modellist(item_Descr.GetFileName())

CREO_APP = 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe'
INPUT_DIR = 'E:/python/test_data/'
print('开始连接')
cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
print('建立连接')

AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
try:
    AsyncConnection.Session.ChangeDirectory(INPUT_DIR)
    print('已连接')

    '''
    
    AsyncConnection = cAC.Connect('', '', '.', '')
    print(AsyncConnection)
    print(AsyncConnection.IsRunning())
    ConnectionIds = AsyncConnection.GetConnectionId()
    #print(ConnectionIds)
    print(ConnectionIds.ExternalRep)
    '''
    filename = 'sxio.asm'
    file2name = '6800_frame.asm'
    drwname = 'acdc_insulating_mat.drw'
    formatname = 'D:/PTC/config/format/a3_h.frm'
    #ChangeDrwFormat(drwname, formatname)
    get_modellist(filename)




    '''
    for item in items:       
        print("Device:        ", item.ModelDescr.Device)            #E
        print("FileVersion:   ", item.ModelDescr.FileVersion)       #6
        print("Host:          ", item.ModelDescr.Host)
        print("InstanceName:  ", item.ModelDescr.InstanceName)      #6800_FRAME
        print("Path:          ", item.ModelDescr.Path)              #\\00A30\\002testvbapi\\
        print("Type:          ", item.ModelDescr.Type)              #0
        print("Extension:     ", item.ModelDescr.GetExtension())    #asm
        print("FileName:      ", item.ModelDescr.GetFileName())     #6800_FRAME.asm
        print("GetFullName:   ", item.ModelDescr.GetFullName())     #6800_FRAME
    
    BomExportInstruction = client.Dispatch(VBAPI.CCpfcBOMExportInstructions).Create()
    model.Export('bom.xlsx', BomExportInstruction)
    
    para_value = model.GetParam('PTC_COMMON_NAME').Value
    para_type = para_value.discr
    print('COMMON_NAME', get_paraval(para_value, para_type))
    
    for i in range(0, model.ListParams().Count-1):
        #print(model.ListParams().Item(i).Description)
        try:
            print(i)
            print('Name', model.ListParams().Item(i).Name)
            para_value = model.ListParams().Item(i).Value
            para_type = para_value.discr
            print('Value', get_paraval(para_value, para_type))
            #print('GetValue', model.ListParams().Item(i).Type)
    
            try:
                model.ListParams().Item(i).Delete()
            except Exception as e:
                print(e)
                print('Error!')
    
        except Exception as e:
            print(e)
    
    model.Save()
    print('模型已保存')
    #print(model.ListTables())
    #print(model.ListParams())
    #print(model.Relations)
    '''
except Exception as e:
    print(e)
    print(traceback.print_exc())
finally:
    AsyncConnection.End()
